package com.alibaba.moco;



import javax.servlet.http.HttpServletRequest;

import com.alibaba.moco.util.BaseTypeUtil;

import groovy.lang.GroovyObject;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;
import net.sf.json.JSONObject;

import java.io.*;

public  class MocoScriptRunner  {

	
	
	/**
	 * 
	 * @param request
	 * @param scriptName
	 * @return
	 */
	public static Object excuteScript(HttpServletRequest request, String scriptName) throws IOException, ResourceException, ScriptException, IllegalAccessException, InstantiationException {
			//System.out.println(BaseTypeUtil.getClassPath());
			GroovyScriptEngine engine = new GroovyScriptEngine(BaseTypeUtil.getClassPath());
			Class<?> scriptClass = engine.loadScriptByName(scriptName + ".groovy");
			
			GroovyObject scriptInstance = (GroovyObject) scriptClass
					.newInstance();
			Object res = scriptInstance.invokeMethod("excute", request);
			return res;

	}

	public static Object excuteJson(String jsonName) throws IOException {
        File filename = new File(BaseTypeUtil.getClassPath() + jsonName + ".json"); // 要读取以上路径的input。txt文件
        InputStreamReader reader = new InputStreamReader(
                new FileInputStream(filename)); // 建立一个输入流对象reader
        BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
        StringBuilder jsonBuilder = new StringBuilder();

        String line = br.readLine();
        while (line != null) {
            jsonBuilder.append(line);
            line = br.readLine();

        }
		System.out.println(jsonBuilder.toString());
        return JSONObject.fromObject(jsonBuilder.toString());

    }
}

